<?php
namespace Zxf5115\Laravel\Complain\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Zxf5115\Laravel\Kernel\Traits\ValidatorTrait;
use Zxf5115\Laravel\Complain\Logics\ComplainLogic;
use Zxf5115\Laravel\Kernel\Controllers\Api\ApiController;

/**
 * @author zhangxiaofei [<1326336909@qq.com>]
 * @dateTime 2025-10-08
 *
 * 投诉控制器类
 */
class ComplainController extends ApiController
{
  use ValidatorTrait;

  /**
   * 模型类名
   */
  protected string $modelClass = 'Zxf5115\Laravel\Complain\Models\Api\Complain';

  /**
   * 允许客户端查询的字段
   */
  protected array $allowParams = [
    'category_id',
  ];

  /**
   * 关联预加载配置
   */
  protected array $withRelations = [
    'category'
  ];

  /**
   * 操作投诉信息
   *
   * @param Request $request 用户请求参数
   * @param ComplainLogic $logic 投诉逻辑对象
   * @return JsonResponse 响应数据
   */
  public function handle(Request $request, ComplainLogic $logic) : JsonResponse
  {
    try
    {
      $messages = [
        'category_id.required' => '请您选择投诉分类',
        'content.required' => '请您输入投诉内容',
      ];

      $rules = [
        'category_id' => 'required',
        'content' => 'required',
      ];

      // 验证用户数据内容是否正确
      $validation = $this->validation($request, $messages, $rules);

      if(!$validation['status'])
      {
        return error($validation['message']);
      }

      // 投诉数据处理
      $logic->handle($request, $this->modelClass);

      return success(__('kernel.handle_success'));
    }
    catch(\Exception $e)
    {
      // 记录异常信息
      record($e);

      return error(__('kernel.handle_failure'));
    }
  }
}
